/**
 * 公共JS 对象
 * 
 * @author cdzhangwei3
 * @time   2014-01-17
 */	

//定义JS命名空间
var Namespace = Namespace||new Object();
Namespace.register = function(path){var arr = path.split("."),ns = "";for(var i=0;i<arr.length;i++){if(i>0){ns += ".";}ns += arr[i];eval("if(typeof(" + ns + ")=='undefined'){" + ns + " = new Object();}");}};

//定义JS 公共组件（该组件中包含了基本打方法,ajax请求,遮罩...）
Namespace.register("Dashboard");
(function(){
	
	Dashboard.swfupload = null;
	Dashboard.rootUrl="";
	Dashboard.staticUrl="";
	Dashboard.fullScreenFlag=false;
	Dashboard.consoleCss=null;
	Dashboard.defaultH=0;
	Dashboard.consolePlatform=null;
	
	
	/**
	 *开启一个遮罩层
	 * @params{String} info 提示信息 
	 */
	Dashboard.mask = function(info){
		if($("#winModal,#loadInfo").length == 0) {var msg = (info != null && info.trim() != "") ? info:"系统正在为您处理数据,请稍候...";$("body").append("<div id='winModal'></div><div id='loadInfo'>"+msg+"</div>");}
	};
	
	/**
	 *关闭一个遮罩层 
	 */
	Dashboard.unmask = function(){
		$("#winModal,#loadInfo").remove();
	};
	
	//check content is empty 
	Dashboard.checkContent=function(str){
		return str==null||str=="undefined"||str=="";
	};
	
	//将内容复制到剪切版
	Dashboard.copyToClipBoard = function(str){
		try{
			window.clipboardData.setData("Text",str);     
			alert("已复制到剪贴板");  
		}catch(e){
			//console.log("复制内容到剪切板出错:"+e);
		}
	};
	
	/**
	 * 公共的ajax请求数据方法
	 * 
	 * @param {String} url 请求地址
	 * @param {Object} params 传递参数Object类型
	 * @param {boolean} ismask 是否开启遮罩
	 * @param {function} suc 处理成功的回调函数
	 * @param {function} err 处理失败的回调函数
	 */
	Dashboard.reqAjax = function(url,params,ismask,suc,err){
		if(ismask){
			Dashboard.mask();
		}
		$.ajax({url : Dashboard.rootUrl+url,type:"POST",data:params,dataType:"json",
			beforeSend: function(xhr){xhr.setRequestHeader('response-type', 'json');},
			success:function(response){
				Dashboard.unmask();
				if(response["RES_STATUS"]=='fail'){//出错了
					if(typeof(err)=="function"){
						err(response["RES_MSG"],response);
					}else{
						alert(response["RES_MSG"]);
					}
					//console.log("Dashboard.reqAjax fail. url:"+url+",param:"+params+",response:"+response);
					return;
				}
				if(typeof(suc)=="function"){
					suc(response["RES_MSG"],response);
				}else{
					alert(response["RES_MSG"]);
				}
			},
			error:function(jqXHR,textStatus,errorThrown){
				Dashboard.unmask();
				//console.log("Dashboard.reqAjax fail. url:"+url+",param:"+params+",e:"+textStatus);
				if(typeof(err)=="function"){
					err("请求失败,httpStatus:"+textStatus);
				}
			}
		});
	};
	
	/**
	 *init page execute init function 
	 * use:
	 * 在html代码中通过定义 <SPAN class='script' page-load="function name"></SPAN>
	 */
	Dashboard.initPage = function(){
		try{
			$("SPAN.script").each(function(i,o){
				eval($(o).remove().attr("page-load"));
			});
		}catch(e){
			//console.log("页面初始化失败:"+e);
		}
	};
	
	/**
	 *动态加载指定容器打内容
	 *  @params{string} containerId 容器ID
	 *  @params{string} url 请求地址
	 *  @params{Object}	 params 请求参数
	 */
	Dashboard.loadContainer = function(containerId,ismark,url,params,callback){
		if(ismark){Dashboard.mask();}
		jQuery.post(Dashboard.rootUrl+url,params,function(data){
			try{callback();}catch(e){
				//console.log("locadContainer execute callBack fail:"+e);
				}
			try{$("#"+containerId).html(data);}catch(e){
				//console.log("loadContainer.sethtml fail:"+e);
				}
			if(ismark){Dashboard.unmask();}
			Dashboard.initPage();
		});
	};
	
  //最小化控制台
  Dashboard.min_console_log=function(){
	$('.dialog-title a.max').removeClass('max').addClass('resize');
	$('.console h3').show();
	Dashboard.consolePlatform.css(Dashboard.consoleCss.minScreen);
	$('.top_control').css('bottom','0');
	Dashboard.fullScreenFlag = false;
  };
  
  //最大化控制台或全屏
  Dashboard.max_console_log = function(){
	if($('.dialog-title a').hasClass('resize')){
		Dashboard.consolePlatform.css(Dashboard.consoleCss.maxScreen);					
		$('.dialog-title a.resize').removeClass('resize').addClass('max');
		Dashboard.fullScreenFlag = false;
	}else if($('.dialog-title a').hasClass('max')){
		Dashboard.consolePlatform.css(Dashboard.consoleCss.fullScreen);
		$('.dialog-title a.max').removeClass('max').addClass('resize');
		Dashboard.fullScreenFlag = true;
	}
  };
  
  //初始化控制台参数
  Dashboard.initConsoleData = function(){
  	Dashboard.defaultH = $(window).height();
	Dashboard.consoleCss = {
		fullScreen : {
			top : 0,
			height : Dashboard.defaultH
		},
		minScreen : {
			top : Dashboard.defaultH - 42,
			height : 42
		},
		maxScreen : {
			top : Dashboard.defaultH - 230,
			height : 230
		}
	};	
  };
  
  //清空控制台日志信息
  Dashboard.clean_console_log = function(){
  	$("#console_log_info").html("");
  };

})();

//控制台实时日志
Namespace.register("Dashboard.Log");
(function(){
	
	Dashboard.Log.curr_appId = null;//当前选中的应用ID
	Dashboard.Log.curr_instanceId = null;//当前选中的应用的实例ID
	Dashboard.Log.open = false;//日志开关是否打开
	Dashboard.Log.app_log_param = null;//应用日志采集参数
	Dashboard.Log.task_log_param = null;//当前tail task日志的参数
	Dashboard.Log.task_log = false;//是否tail task 日志
	Dashboard.Log.timer_tail_open = false;//是否已经开启timer 实时采集日志
	Dashboard.Log.console_log_max_num = 1000;//控制台最多保留日志行数
	
	//清空实时日志下拉列表
	Dashboard.Log.cleanItem = function(){
		$("#console_item_container").html("");
	};
	//添加应用到实时日志下拉列表
	Dashboard.Log.addItem = function(name,appId){
		var itemId = "console_item_li_"+appId;
		if($("#"+itemId).length <=0){//实例不存在
			var show_item =name;
	  		if(name.length>=12){show_item = name.substr(0,12)+"...";} 
	  		$(".selectdrop > li").removeClass("current");
	  		var itemObj = $("<li class='console_item_li current' id='"+itemId+"' app_name='"+name+"' app_id='"+appId+"' app_name='"+name+"' >"+show_item+"</li>");
	  		$(itemObj).unbind().bind("click",function(){
	  			$(".selectdrop > li").removeClass("current");
	  			$(this).addClass("current");
	  			$("#select_app_log").html(name);
	  			Dashboard.Log.curr_appId = $(this).attr("app_id");
	  			//探测应用对应的日志实例信息
	  			$("#console_instance_container").html("");
	  			Dashboard.reqAjax("console/findLogInstance",{"appName":$(this).attr("app_name")},false,function(msg,data){
			  		var instances = data.instances;
			  		for(var i=0;i<instances.length;i++){
			  			var ins = instances[i];
			  			var insObj = null;
			  			var param = {"host":ins.ip,"appName":data.appName,"instance":ins.instanceId,"file":1,"pos":0,
									"currState":2,"state1":2,"state2":2,"state3":2,"pos1":-100,"pos2":-100,"pos3":-100};
			  			if(i ==0){
			  				Dashboard.Log.curr_instanceId = ins.instanceId;
			  				Dashboard.Log.app_log_param = param;
			  				insObj = $("<li class='current' id='"+ins.instanceId+"' data='"+JSON.stringify(param)+"' >实例"+(i+1)+"</li>");
			  			}else{
			  				insObj = $("<li id='"+ins.instanceId+"' data='"+JSON.stringify(param)+"' >实例"+(i+1)+"</li>");
			  			}
			  			$(insObj).unbind().bind("click",function(){
			  				Dashboard.Log.curr_instanceId = $(this).attr("id");
			  				$(".selectdrop2 > li").removeClass("current");
				  			$(this).addClass("current");
			  				if(Dashboard.Log.open){Dashboard.Log.app_log_param = JSON.parse($(this).attr("data"));Dashboard.Log.timer_tail();}
			  			});
			  			
			  			$("#console_instance_container").append(insObj);
			  			if(Dashboard.Log.open){Dashboard.Log.timer_tail();}
			  		}
	  				if(instances.length >1){$("#ins_selectdiv2").css("display","");}else{$("#ins_selectdiv2").css("display","none");}
	  					
			  	},function(msg,data){
//			  		console.log("console findLogInstance fail:"+msg);
			  	});
	  		});
	  		$("#console_item_container").append(itemObj);
		}
		$(".selectdrop > li").removeClass("current");
	  	$("#console_item_li_"+Dashboard.Log.curr_appId).addClass("current");
	};
	
	//开启或关闭日志
	Dashboard.Log.on_off_log = function(){
		$("#on_off_log_btn > .switch-animate").toggleClass('switch-off');
		if($('.switch-animate').hasClass('switch-off')){
			$('#switch').attr('checked',false);
			$('.switch-title').html('已关闭').css('color','#999');
			$('.switch-animate').removeClass('switch-on');
		}else{
			$('#switch').attr('checked',true);
			$('.switch-title').html('已开启').css('color','#41A7C5');
			$('.switch-animate').addClass('switch-on');
		}
		
		var open_flag = $("#on_off_log_btn").attr("open_flag");
		if("off"==open_flag){//开启日志
			Dashboard.Log.open = true;
			$("#on_off_log_btn").addClass("run");
	  		$("#on_off_log_btn").attr("title","已开启,点击关闭日志");
	  		$("#on_off_log_btn").attr("open_flag","on");
	  		if($('.dialog-title a').hasClass('resize') &&Dashboard.fullScreenFlag!=true){//判断是否需要打开日志控制台
		  		Dashboard.max_console_log();
		  	}
		  	//判断是否需要提醒用户选择应用
		  	if(Dashboard.Log.curr_appId==null){
				if($("#console_item_container > li").length >0 ){
		  		   $("#console_item_container li:first").trigger("click");
		  		}else{
		  		   var obj =$("<ol><li>应用日志已开启,请在[应用名称]下面选择需要显示日志的应用</li></ol>");
		  		   $("#console_log_info").append(obj);
		  		}
		  	}else{
		  		Dashboard.Log.timer_tail();//开始tail日志
		  	}
		}else{//关闭日志
			$("#on_off_log_btn").removeClass("run");
	  		$("#on_off_log_btn").attr("title","已关闭,点击开启日志");
	  		$("#on_off_log_btn").attr("open_flag","off");
	  		Dashboard.Log.open = false;
	  		Dashboard.Log.close_timer_tail();//关闭日志
		}
	};
	
	//tail 任务日志
	Dashboard.Log.tailTaskLog = function(messageKey, taskId, appId){
		Dashboard.Log.task_log_param = {"message_key":messageKey,"task_id":taskId,"app_id":appId};//当前tail task日志的参数
		Dashboard.Log.task_log = true;//是否tail task 日志
		$("#console_item_li_"+appId).trigger("click");
		Dashboard.Log.timer_tail();
	};
	
	//开启实时tail日志,默认3秒tail一次日志
	Dashboard.Log.timer_tail = function(){
		Dashboard.Log.close_timer_tail();//关闭实时tail日志
		if(Dashboard.Log.timer_tail_open){return;}
		Dashboard.Log.timer_tail_open = true;
		
		$("body").everyTime("3s","tail_log",function(){
			Dashboard.Log.tailLog();
	  	});
	};
	
	//关闭实时tail日志
	Dashboard.Log.close_timer_tail = function(){
		Dashboard.Log.timer_tail_open = false;
		$("body").stopTime("tail_log");
	};
	
	//判断是否清楚当前正在tail日志的参数
	Dashboard.Log.cleanCurrTailParm = function(appname){
		try{
			if (Dashboard.Log.app_log_param["appName"] == appname){
				Dashboard.Log.app_log_param = null;
				Dashboard.Log.curr_instanceId = null;
			}
		}catch(e){}
	};
	//tail 日志
	Dashboard.Log.tailLog = function(){
		
		if(!Dashboard.Log.open){return ;}
		
		if(Dashboard.Log.task_log == true && Dashboard.Log.task_log_param != null){//tail任务日志
			Dashboard.reqAjax("console/tasklog",Dashboard.Log.task_log_param,false,function(msg,data){
		  		$("#log_info_task_ol").remove();
		  		$("#console_log_info").append($("<ol id='log_info_task_ol'><li>"+data.log+"</li></ol>"));
		  		$("#console_log_info").scrollTop($("#console_log_info")[0].scrollHeight);
		  		if(data.isfinsh=="true"){
		  			if(data.iserror =="false"){
		  				$("#console_item_li_"+Dashboard.Log.task_log_param.app_id).trigger("click");
		  			}else{
		  				Dashboard.Log.app_log_param = null;
						Dashboard.Log.curr_instanceId = null;
		  			}
		  			Dashboard.Log.task_log = false;
		  			Dashboard.Log.task_log_param = null;
		  		}
		  	},function(msg,data){
//		  		console.log("tail task log fail:"+msg);
		  	});
		}else{//tail 实时日志
			if(Dashboard.Log.app_log_param != null && Dashboard.Log.curr_instanceId != null){
				Dashboard.reqAjax("console/gatherlog",Dashboard.Log.app_log_param,false,function(msg,data){
		  			
					//判断是否要重新加载实例信息
					if(data.refashInstance == "true"){
						$("#console_item_li_"+Dashboard.Log.curr_appId).trigger("click");
						Dashboard.Log.close_timer_tail();
						return;
					}
					var curr_log_lines = $("#console_log_info >ol").length;
		  			if(curr_log_lines >Dashboard.Log.console_log_max_num){//清空多余的日志信息
		  				$("#console_log_info >ol:lt("+(curr_log_lines-Dashboard.Log.console_log_max_num)+")").remove();
		  			}
			  		var logs = data.logs;
			  		Dashboard.Log.app_log_param = {"host":data.host,"appName":data.appName,"instance":data.instanceId,"file":data.nextFile,"pos":data.nextPos,
			  										"currState":data.nextState,"state1":data.state1,"state2":data.state2,"state3":data.state3,"pos1":data.pos1,"pos2":data.pos2,"pos3":data.pos3};
			  		$("#instance_"+Dashboard.Log.curr_instanceId).attr("data",JSON.stringify(Dashboard.Log.app_log_param));
			  		
			  		for(var i=0;i<logs.length;i++){
			  			$("#console_log_info").append($("<ol><li>"+logs[i]+"</li></ol>"));
			  		}
			  		if(logs.length>0){
			  			$("#console_log_info").scrollTop($("#console_log_info")[0].scrollHeight);
			  		}
			  	},function(msg,data){
//			  		console.log("tail gather log fail:"+msg);
			  	});
			}
		}
	};
	
	
})();

//订阅dashboard任务框架,主要用于检查任务状态,任务回调函数
Namespace.register("Dashboard.task");
(function(){
	
	Dashboard.task.timers = new Array();//存储当前所有的check timer
	Dashboard.task.calls = {};//任务执行完成后的回调函数,taskId=function(task_status),task_status:1->完成,2->异常
	
	//注册任务任务的回调,回调函数接收一个任务状态参数,如: function(task_status),task_status:1->完成,2->异常
	Dashboard.task.registerFinishCall = function(appid,fun){
		if(Dashboard.task.calls[appid]){Dashboard.task.calls[appid] == null;}
		if(typeof(fun)=="function"){Dashboard.task.calls[appid] = fun;}else{
			//console.log("task.registerFinishCall fail,call is not function");
		}
	};
	
	//显示任务检查的进度条
	Dashboard.task.showCheckTask = function(appId){
		$("#percent_cont_"+appId).css("display","");
		Dashboard.task.addCheckTask({appId:appId,messageKey:appId});
	};
	
	//添加一个需要检查状态的任务
	Dashboard.task.addCheckTask = function(response){
		var appId = response.appId;
		var msgKey = response.messageKey;
		var timerId = "ckTimer_"+appId;
		
		Dashboard.task.timers.push(timerId);
		$("#percent_cont_"+appId).css("display","");
		$("body").stopTime(timerId);
		$("body").everyTime("3s",timerId,function(){
			Dashboard.task.check_task(timerId, appId);
	  	});
		Dashboard.Log.tailTaskLog(msgKey,0,appId);
	};
	
	//清空所有的任务检查timer
	Dashboard.task.cleanTimer = function(){
		for(var i=0;i<Dashboard.task.timers.length;i++){
			$("body").stopTime(Dashboard.task.timers[i]);
		}
	};
	
	//检查任务
	Dashboard.task.check_task = function(timerId,appId){
		Dashboard.reqAjax("console/checkTask",{"appId":appId},false,function(msg,data){
			
			var percent  = data.percent;
			var isfinish = data.isfinish;
			var desc     = data.desc;
			var status   = data.status;
			var appName  = data.appName;
			var percents = data.percent_msg;
			
			if(isfinish == "finish" || isfinish=="fail"){//任务已经完成
				$("body").stopTime(timerId);
				try{
					if(typeof(Dashboard.task.calls[appId])=="function" && isfinish == "finish"){//执行回调函数
						Dashboard.task.calls[appId](status);
					}else{
						if(isfinish == "finish"){alert(desc+"["+appName+"] 成功");}else {alert(desc+"["+appName+"] 失败");}
					}
				}catch(e){
				}
				Dashboard.task.calls[appId] = null;
				$("#percent_cont_"+appId).css("display","none");
				Dashboard.index.getAppList(false);//重新加载应用列表
				Dashboard.index.getUserInfo(false);//重新加载配额
			}else{
				$("#percent_cont_"+appId).css("display","");
//				$("#app_status_"+appId).html("<font color='blue'>正在"+desc+"</font>");
				$("#app_percent_"+appId).css("width",percent+"%");
				$("#app_percent_"+appId).html("[正在"+desc+"]:"+percents+"%");
			}
			
	  	},function(msg,data){
	  		//console.log("Dashboard task check_task fail:"+msg);
	  	});
	};
	
})();

//定义Dashboard表单框架
Namespace.register("Dashboard.form");
(function(){
	
	/**
	 * ajax 方式提交form表单
	 * @param {string} formName 
	 * @param {function} suc
	 * @param {function} err 
	 */
	Dashboard.form.postAjax= function(formName,suc,err){
		Dashboard.mask();
		var form = $("form[name="+formName+"]");
		if(!form){
			aleret("表单提交失败,请检查form是否合法");
			Dashboard.unmask();
			return;
		}
		var href = $(form).attr("action");
		$.ajax({
			url : href,
			type : $(form).attr("method"),
			data : $(form).serialize(),
			dataType:"json",
			beforeSend: function(xhr){xhr.setRequestHeader('response-type', 'json');},
			success : function(response) {
				Dashboard.unmask();
				if(response["RES_STATUS"]=='fail'){//出错了
					if(typeof(err)=="function"){
						err(response["RES_MSG"],response);
					}
				}else{
					if(typeof(suc)=="function"){
						suc(response["RES_MSG"],response);
					}
				}
			},
			error:function(jqXHR,textStatus,errorThrown){
				Dashboard.unmask();
				//console.log("Dashboard.form.postAjax fail. form_name:"+formName+",e:"+textStatus);
				alert("数据处理失败");
			}
		});
	};
})();

//定义Dashboard window 组件
Namespace.register("Dashboard.window");
(function(){
	//窗口默认配置项
	var DEF_OPTS = {buttons:[],width :'auto',height :'auto',iconCls:'',modal:true,moveable:true,resizable:true,closeable:true,maxable:false,minable:false};
	var ZINDEX_MAX_VALUE = 2000;//窗口层级最大值
	var ACTIVE_WINDOW = null;//当前活动窗口
	Dashboard.window.queue = new Array();
	Dashboard.window.callback={};
	//打开对话框
	Dashboard.window.openDialog = function(title,content,options,closeCall){
		
		options=$.extend(true, {}, DEF_OPTS, options || {});//合并配置
		var winOpts = {"id":"win-"+(new Date()).getTime()};//记录窗口的基本信息
		
		//定义窗口网页对象
		var backdrop = $('<div class="modal-backdrop fade in"/>');
		var modal = $("<div class='window'></div>").attr("id",winOpts.id);
		var panel = $("<div class='panel'></div>");
		var panelHeader = $("<div class='panel-heading'></div>");
		var panelBody = $("<div class='panel-body' id='panel_body_content'></div>");
		var panelTool = null,panelFooter = null;
		
		//事件按钮
		if(options.closeable){panelHeader.append("<i class='close closeBtn' title='\u5173\u95ed'></i>");}
		if(options.maxable){panelHeader.append("<i class='close maxBtn' title='\u6700\u5927\u5316'></i>");}
		if(options.minable && !options.modal){panelHeader.append("<i class='close minBtn' title='\u6700\u5c0f\u5316'></i>");}
		//logo与标题
		if(options.iconCls){panelHeader.append($("<i/>").addClass(options.iconCls));}
		panelHeader.append(title);
		
		//添加内容并添加底部（顶部）按钮组
		panelBody.append(content).find("DIV.bottomBar>button.btn,DIV.bottomBar>A.btn").each(function(i,o){options.buttons.push(o);});
		if(panelBody.find("DIV.topBar").length == 1){panelTool=panelBody.find("DIV.topBar").addClass("yarnball panel-tool");panelBody.css({"border-top-left-radius":"0px","border-top-right-radius":"0px"});}
		if(options.buttons != null && options.buttons.length > 0) {panelFooter = $("<div class='panel-footer'></div>");for(var btn in options.buttons){panelFooter.append(options.buttons[btn]);}panelBody.css({"border-bottom-left-radius":"0px","border-bottom-right-radius":"0px"});}
		//设置窗口属性并添加在页面显示
		modal.css({"width":options.width,"height":options.height,"z-index":++ZINDEX_MAX_VALUE}).append(panel.append(panelHeader).append(panelTool).append(panelBody).append(panelFooter)).appendTo(document.body);
		//模态窗口
		if(options.modal){modal.before(backdrop.css("z-index",ZINDEX_MAX_VALUE-1));options.minable=false;}
		
		//内部方法刷新窗口,大小等
		var refreshModal = function(){
			var width = modal.width(),height = modal.height(),sub=26;
			if(panelTool&&panelFooter){sub=97;}
			if(!panelTool&&panelFooter){sub=70;}
			if(panelTool&&!panelFooter){sub=27;}
			
			panelBody.css({"width":width,"height":height - sub});$(window).resize();};
			
		//调整窗口大小
		if(options.resizable){modal.resizable({containment:document.body,handles:'all',helper: "dottedBoder",minHeight: 138,minWidth: 200,start: function( event, ui ) {ui.element.find("iframe").hide();},stop: function( event, ui ) {ui.element.find("iframe").show();refreshModal();}});}
		//窗口拖动
		if(options.moveable){modal.draggable({handle: panelHeader,cursor:"move",opacity: 0.5,start: function( event, ui ) {ui.helper.find("iframe").hide();},stop: function( event, ui ) {ui.helper.find("iframe").show();}});}
		//关闭窗口
		if(options.closeable){var closeMethod = function(){try{var call =Dashboard.window.callback[panelHeader.find(".closeBtn").attr("close_callback")]; if(call!=null){call();return;}}catch(e){} try{ modal.hide().remove();backdrop.remove();}catch(e){} if(options.width!=330){Dashboard.window.queue.pop();}};panelHeader.find(".closeBtn").bind("click",closeMethod);}
		panelHeader.find(".closeBtn").attr("close_callback",closeCall);
		//窗口最大化,还原
		if(options.maxable){var maxMethod = function(){var maxBtn = panelHeader.find(".maxBtn"),isMax = maxBtn.hasClass("open"),dsktp = $(document.body),left=0,top=0,width=dsktp.width(),height=dsktp.height();if(isMax){if(options.resizable){modal.resizable("enable");}if(options.moveable){modal.draggable("enable");}left=winOpts.left;top=winOpts.top;height=winOpts.height;width=winOpts.width;$(maxBtn).removeClass("open").attr("title","\u6700\u5927\u5316");} else {if(options.resizable){modal.resizable("disable");}if(options.moveable){modal.draggable("disable");}var offset = modal.offset();winOpts.left=offset.left;winOpts.top=offset.top;winOpts.height=modal.height();winOpts.width=modal.width();$(maxBtn).addClass("open").attr("title","\u8fd8\u539f\u6700\u5927\u5316");}modal.css({"left":left,"top":top,"width":width,"height":height}).show(refreshModal);};panelHeader.bind("dblclick",maxMethod).find(".maxBtn").bind("click",maxMethod);}
		//最小化窗口
		if(options.minable){panelHeader.find(".minBtn").bind("click",function(){modal.hide().click();});}
		//窗口点击更改zIndex
		modal.bind("click",function(e){ACTIVE_WINDOW = modal;var zIndex = modal.css("z-index");if(options.minable){if(zIndex<ZINDEX_MAX_VALUE){modal.css("z-index",++ZINDEX_MAX_VALUE);}}}).bind("mousedown",function(){$(this).click();});
		
		//打开时延迟一会显示并刷新窗口
		var winShow = function(){var left =($(window).width() - modal.width())/2;var top =($(window).height() - modal.height())/2 - 30;modal.css({"top":top,"left":left}).show();refreshModal();Dashboard.initPage();};
		setTimeout(winShow,50);
		if(options.width!=330){
			Dashboard.min_console_log();
			Dashboard.window.queue.push(modal);
		}
		
		//判断是否时alert提示框
		if(options.altFlag){
			$("body").everyTime("1s","close_alert_win",function(){
		  		try{
		  			var a = modal.find('DIV.panel-footer>A>I.glyphicon-alert');
		  			var time_s =parseInt(a.attr("time_s"));
		  			if ( time_s==2){
		  				a.click();
		  				$("body").stopTime("close_alert_win");
		  			}else{
		  				time_s+=1;
		  				a.attr("time_s",time_s);
		  				modal.find('DIV.panel-footer>A>SPAN.alt_info').html("确定("+(3-time_s)+"秒后自动关闭)");
		  			}
		  			
		  		}catch(e){
		  			//console.log("提示框定时停止失败:"+e);
		  			}
		  	});
		}
		return ACTIVE_WINDOW = modal;
	};
	
	//关闭当前活动窗口
	Dashboard.window.closeActive = function() {
		$("body").stopTime("close_alert_win");
		var length = Dashboard.window.queue.length;
		try {if(length>0){Dashboard.window.queue[length-1].find('DIV.panel-heading>I.closeBtn').click();}}catch(e){
			//console.log("关闭窗口失败:"+e);
			}
		try{ACTIVE_WINDOW.find('DIV.panel-heading>I.closeBtn').click();}catch(e){
			//console.log("关闭窗口失败:"+e);
			}
	};
	//confirm 确认
	Dashboard.window.confirmOk = function(){
		$("body").stopTime("close_alert_win");
		try{ACTIVE_WINDOW.find('DIV.panel-footer>A>I.glyphicon-ok').click();}catch(e){
			//console.log("打开确认框失败:"+e);
			}
	};
	//提示窗口
	Dashboard.window.alert = function(msg,callback,option){
		var opt ={"default":false,width:330,height:150,iconCls:'glyphicon glyphicon-volume-up',modal:true,moveable:true,resizable:false,closeable:true,maxable:false,minable:false,altFlag:true};
		option=$.extend(true,{},opt,{});//合并配置
		var ok = $("<a class='btn btn-primary btn-xs'><i class='glyphicon glyphicon-ok glyphicon-alert' time_s='0'/> <span class='alt_info'>"+(option.okText||"确定(2秒后自动关闭)")+"</span></a>");
		option.buttons = [ok];
		var modal = Dashboard.window.openDialog("\u7cfb\u7edf\u63d0\u793a",msg,option);
		ok.bind("click",function(e){try{callback();}catch(x){}modal.find("DIV.panel-heading>I.closeBtn").click();});
	};
	
	Dashboard.window.confirm = function(msg,callback,option){
		var opt ={"default":false,width:330,height:150,iconCls:'glyphicon glyphicon-question-sign',modal:true,moveable:true,resizable:false,closeable:true,maxable:false,minable:false};
		option=$.extend(true, {},opt,{});//合并配置
		var ok = $("<a class='btn btn-primary btn-xs'><i class='glyphicon glyphicon-ok glyphicon-confirm'/> "+(option.okText||"\u786e\u5b9a")+"</a>");
		var cancel = $("<a class='btn btn-primary btn-xs'><i class='glyphicon glyphicon-remove'/> "+(option.cancelText||"\u53d6\u6d88")+"</a>");
		option.buttons = [ok,cancel];
		var modal = Dashboard.window.openDialog("\u7cfb\u7edf\u63d0\u793a",msg,option);
		var close = function(e){modal.find("DIV.panel-heading>I.closeBtn").click();};
		ok.bind("click",function(e){try{callback(true);}catch(x){}close(e);});
		cancel.bind("click",function(e){try{callback(false);}catch(x){}close(e);});
		return false;
	};
	
	//打开Ajax窗口
	Dashboard.window.openAjaxWindow = function(title,url,params,method,option,closeCall){
		Dashboard.mask();
		var open = function(data) {
			Dashboard.unmask();
			//弹出提示框
			Dashboard.window.openDialog(title,data,option,closeCall);
		};
		if("POST" == method) {
			jQuery.post(Dashboard.rootUrl+url,params,open);
		} else {
			jQuery.get(Dashboard.rootUrl+url,params,open);
		}
	};
	
})();

//init method
$(document).ready(function() {
	ZeroClipboard.setMoviePath(Dashboard.staticUrl+"/js/console/ZeroClipboard10.swf");
	$(document.body).bind("keyup",function(event){
		if(event.keyCode == 27) {Dashboard.window.closeActive();}
		else if(event.keyCode == 13){Dashboard.window.confirmOk();}//回车键默认是确认按钮
	});
	window.alert = Dashboard.window.alert;
	window.confirm = Dashboard.window.confirm;
	var oH = $(window).height();
	var cH = $("#content_container").height();
	if(oH>cH){
		$(".left_menu").height(oH-100);
	}else{
		$(".left_menu").height(cH);
	}
	
	$('.Modal').css('height', oH);
	$('.dialog-title .selectdiv').hover(function(){
		$('.selectdrop').toggle();
	});
	$('.dialog-title .selectdiv2').hover(function(){
		$('.selectdrop2').toggle();
	});
	//隐藏baidu分析图标
	$("a").find("[src='http://eiv.baidu.com/hmt/icon/21.gif']").hide();
	//注册document双击事件
	$(window.document.body).dblclick(function(event){
		try{
			oEvent = event || window.event;
    		var target = oEvent.target || oEvent.srcElement;
    		
    		if($(target).hasId("console_log_info")){
    			return false;
    		}
    		
			if(!$(target).hasClass("dialog-title")){
				Dashboard.min_console_log();
				event.stopPropagation();
			}
		}catch(e){
			//console.log("body dbclick fail:"+e);
			}
	});
});
(function(a){
	a.fn.hoverClass=function(b){
		var a=this;
		a.each(function(c){
			a.eq(c).hover(function(){
				$(this).addClass(b);
			},function(){
				$(this).removeClass(b);
			});
		});
		return a;
	};
})(jQuery);
